<template>
  <v-dialog
    v-model="dialogFormVisible"
    max-width="800px"
    persistent
  >
    <v-card>
      <v-card-title>
        <span>{{ title }}</span>
      </v-card-title>
      
      <v-card-text>
        <v-form ref="formRef" v-model="valid">
          <v-row>
            <v-col cols="12" md="6">
              <v-text-field
                v-model="form.typeCode"
                label="字典类型编号"
                :rules="typeCodeRules"
                required
                variant="outlined"
                density="compact"
              ></v-text-field>
            </v-col>

            <v-col cols="12" md="6">
              <v-text-field
                v-model="form.typeName"
                label="字典类型名称"
                :rules="typeNameRules"
                required
                variant="outlined"
                density="compact"
              ></v-text-field>
            </v-col>

            <v-col cols="12" md="6">
              <v-select
                v-model="form.izLock"
                :items="noYesOptions"
                label="是否内置"
                item-title="dictName"
                item-value="dictValue"
                variant="outlined"
                density="compact"
              ></v-select>
            </v-col>

            <v-col cols="12" md="6">
              <v-textarea
                v-model="form.remark"
                label="备注"
                variant="outlined"
                density="compact"
                rows="3"
              ></v-textarea>
            </v-col>
          </v-row>
        </v-form>
      </v-card-text>

      <v-card-actions>
        <v-spacer></v-spacer>
        <v-btn @click="close">取消</v-btn>
        <v-btn color="primary" @click="save" :loading="saving">确定</v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance } from 'vue';
import { doInsert, doUpdate } from '@/api/system/dict/dictManagement';
import { isNotNull } from '@/utils/validate';
import { useMessage } from '@/composables/useMessage';

const { proxy } = getCurrentInstance();
const { success: showSuccess, error: showError } = useMessage();

// 响应式数据
const dialogFormVisible = ref(false);
const valid = ref(true);
const saving = ref(false);
const title = ref('');
const formRef = ref();

const form = ref({
  typeCode: '',
  typeName: '',
  izLock: '0',
  remark: '',
  version: 0
});

const noYesOptions = ref([]);

// 验证规则
const typeCodeRules = [
  v => !!v || '请输入编号',
  v => /^[a-zA-Z0-9_]+$/.test(v) || '编号格式不正确'
];

const typeNameRules = [
  v => !!v || '请输入名称',
  v => /^[\u4e00-\u9fa5a-zA-Z0-9_\s]+$/.test(v) || '名称格式不正确'
];

// 定义 emits
const emit = defineEmits(['fetchData']);

onMounted(() => {
  // 获取字典数据
  noYesOptions.value = proxy?.$getDictList('no_yes') || [];
});

/**
 * 显示编辑对话框
 */
const showEdit = (row) => {
  if (!row) {
    title.value = '添加';
    form.value = {
      typeCode: '',
      typeName: '',
      izLock: '0',
      remark: '',
      version: 0
    };
  } else {
    title.value = '编辑';
    form.value = { ...row };
  }
  dialogFormVisible.value = true;
};

/**
 * 关闭对话框
 */
const close = () => {
  dialogFormVisible.value = false;
  formRef.value?.resetValidation();
  form.value = {
    typeCode: '',
    typeName: '',
    izLock: '0',
    remark: '',
    version: 0
  };
};

/**
 * 保存数据
 */
const save = async () => {
  if (!formRef.value) return;
  
  const { valid: isValid } = await formRef.value.validate();
  if (!isValid) return;
  
  saving.value = true;
  
  try {
    let response;
    if (isNotNull(form.value.id)) {
      // 修改
      response = await doUpdate(form.value);
    } else {
      // 新增
      response = await doInsert(form.value);
    }
    
    showSuccess(response.msg || '保存成功');
    emit('fetchData');
    close();
  } catch (error) {
    console.error('保存失败:', error);
    showError('保存失败');
  } finally {
    saving.value = false;
  }
};

// 暴露方法
defineExpose({
  showEdit
});
</script>
